import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../utils/Toast.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  // 当前位置
  String currentAddress = '';
  // 附近社区
  List nearbyCommunity = [];
  void _getPermission() async {
    // Permission.location.request() 动态申请位置权限
    PermissionStatus per = await Permission.location.request();
    // if (per == PermissionStatus.granted) {
    //   PromptAction.showSuccessToast("用户已授权地址位置权限");
    //   // _getLocation();
    // } else {
    //   PromptAction.showErrorToast("用户拒绝授权");
    // }
    if (per.isGranted) {
      PromptAction.showSuccessToast("用户已授权地址位置权限");
    } else {
      PromptAction.showErrorToast("用户拒绝授权");
    }
  }

  // 获取用户位置的经纬度
  void _getLocation() async {
    // 获取用户位置的经纬度
    Position p = await Geolocator.getCurrentPosition();
    PromptAction.showToast(p.longitude.toString()); // 获取经度
    PromptAction.showToast(p.latitude.toString()); // 获取纬度
    // web端需要在HTTPS下才能使用定位，这里模拟数据
    _getAddress(p.longitude, p.latitude);
  }

  // 高德地图key
  // 463007fae241b2f3fc5b1ac7f0244999
  // 获取地理位置
  void _getAddress(double longitude, double latitude) async {
    Dio dio = Dio();
    final res = await dio.get(
        GlobalVariable.MAP_BASE_URL + HTTP_PATH.MAP_REVERSE_GEOCODING,
        queryParameters: {
          'key': GlobalVariable.MAP_KEY,
          'location': '$longitude,$latitude',
        });
    if (res.data['status'] == '1') {
      PromptAction.showToast(res.data['regeocode']['formatted_address']);
      setState(() {
        currentAddress = res.data['regeocode']['formatted_address'];
      });
    }
  }

  // 获取附近社区
  void _getNearbyCommunity(double longitude, double latitude) async {
    Dio dio = Dio();
    final res = await dio.get(
        GlobalVariable.MAP_BASE_URL + HTTP_PATH.MAP_NEARBY_COMMUNITY,
        queryParameters: {
          'key': GlobalVariable.MAP_KEY,
          'location': '$longitude,$latitude',
          'keywords': '附近社区',
          'offset': 10,
        });
    if (res.data['status'] == '1') {
      setState(() {
        nearbyCommunity = res.data['pois'];
      });
    }
  }

  // 获取附近社区组件列表
  List<Widget> _getNearbyCommunityList() {
    return nearbyCommunity.map((item) {
      return Container(
        color: Colors.white,
        padding: const EdgeInsets.all(10),
        child: Row(
          children: [
            Expanded(child: Text(item['name'])),
            const Row(
              children: [
                Icon(Icons.arrow_forward_ios, size: 16, color: Colors.black),
              ],
            )
          ],
        ),
      );
    }).toList();
  }

  @override
  void initState() {
    super.initState();
    // 尝试去申请定位权限
    _getPermission(); // 申请定位权限
    // web端需要在HTTPS下才能使用定位，这里模拟数据
    _getAddress(121.595907, 31.035155);
    // 获取附近社区，模拟数据
    _getNearbyCommunity(121.595907, 31.035155);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(currentAddress)),
                const Row(
                  children: [
                    Icon(Icons.location_searching_outlined, color: Colors.blue),
                    SizedBox(width: 2),
                    Text(
                      '重新定位',
                      style: TextStyle(color: Colors.blue),
                    ),
                  ],
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: _getNearbyCommunityList(),
          )
        ],
      ),
    );
  }
}
